﻿//-----------------------------------------------------------------------
// <copyright file="RssActionResult.cs" company="OverrideThis">
//     Copyright (c) 2010 OverrideThis.com
// </copyright>
//-----------------------------------------------------------------------
namespace OverrideThis.ContactManager.WebSite.Infrastructure.ActionResults
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.ServiceModel.Syndication;
    using System.Text;
    using System.Web.Mvc;
    using System.Xml;

    public class RssActionResult<T> : ContentResult
    {
        public RssActionResult(
            Uri uri,
            string title,
            string description,
            IEnumerable<T> items,
            Func<T, string> itemTitle,
            Func<T, string> itemContent,
            Func<T, Uri> itemUri)
        {
            var feedItems = items.Select(
                item => new SyndicationItem(
                    itemTitle(item), 
                    itemContent(item), 
                    itemUri(item),
                    "FeedItemID",  
                    DateTime.Now));
            var feed = new SyndicationFeed(title, description, uri, feedItems);
            var sb = new StringBuilder();
            var rss = new Rss20FeedFormatter(feed);
            using (var writer = XmlWriter.Create(sb))
                rss.WriteTo(writer);
            base.Content = sb.ToString();
            base.ContentType = "application/rss+xml";
        }
    }
}